package com.example.oracle.controller;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StopWatch;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.oracle.entity.ContainerEntity;
import com.example.oracle.service.IContainerService;

/**
 * @description: 控制器
 * @author: geffzhang
 * @date: 2021/06/02
 * @version: v1.0
 */
@RestController
@RequestMapping("/container")
public class ContainerController {

    @Autowired
    private IContainerService iUserService;

    private int nColCount ;

    /**
     * 查询用户列表
     *
     * @return 返回List集合
     */
    @GetMapping("/list")
    public RestResult list() {

        try {

            StringBuilder sbSummer = new StringBuilder();


            StopWatch stopWatch = new StopWatch();
            // 开始时间
            stopWatch.start();

            List<ContainerEntity> list = iUserService.getContainerList();
            //return RestResult.suc(list);
            // 结束时间
            stopWatch.stop();
            // 统计执行时间（秒）
            sbSummer.append("TIMINGDB " + stopWatch.getTotalTimeSeconds()); // %n 为换行


            StopWatch stopWatch2 = new StopWatch();
            StringBuilder sb = new StringBuilder();


            stopWatch2.start();
            sb.append("containerList");
            sb.append("\u0004");

            int  nContainerCount = list.size();
            String[] fieldNames = null;
            if(nContainerCount >0) {
                ContainerEntity o = list.get(0);
                fieldNames = this.getFiledName(o);
                nColCount = fieldNames.length;

                for (int nColIndex = 0; nColIndex < nColCount; nColIndex++) {

                    sb.append(fieldNames[nColIndex]);

                    sb.append(nColIndex != nColCount - 1 ? "\u0001" : "\u0002");
                }
                // 开始时间
                long stime = System.currentTimeMillis();


				/*
				 * try { list.parallelStream()..forEachOrdered(entity ->
				 * sb.append(appendContainer(entity))); } catch (Exception e) {
				 * e.printStackTrace(); }
				 */

                for (int nRow = 0; nRow < nContainerCount; nRow++) {
                    ContainerEntity entity = list.get(nRow);
                    sb.append(appendContainer(entity));
                    if(nRow == nContainerCount -1) {
                        sb.append("\u0003");
                    }
                }
                // 结束时间
                long etime = System.currentTimeMillis();
                // 计算执行时间
                System.out.printf("执行时长：%d 毫秒.", (etime - stime));
            }


            // 结束时间
            stopWatch2.stop();
            // 统计执行时间（秒）
            sbSummer.append("TIMINGSTRING " + stopWatch2.getTotalTimeSeconds());
            sbSummer.append(sb.toString());
            return RestResult.suc(sbSummer.toString());
        } catch (Exception ex) {
            return RestResult.fail(500, "失败了", ex.getMessage());
        }

    }
    
    @GetMapping("/list1")
    public RestResult list1() {

        try {

            StringBuilder sbSummer = new StringBuilder();


            StopWatch stopWatch = new StopWatch();
            // 开始时间
            stopWatch.start();

            List<Map<String, Object>> list = iUserService.getContainerList1();
            // 结束时间
            stopWatch.stop();
            // 统计执行时间（秒）
            sbSummer.append("TIMINGDB " + stopWatch.getTotalTimeSeconds()); // %n 为换行


            StopWatch stopWatch2 = new StopWatch();
            StringBuilder sb = new StringBuilder();


            stopWatch2.start();
            sb.append("containerList");
            sb.append("\u0004");

            int  nContainerCount = list.size();
            String[] fieldNames = null;
            if(nContainerCount >0) {
            	Map<String, Object> o = list.get(0);
            	for(String key:o.keySet()){
            		//keySet获取map集合key的集合  然后在遍历key即可
            		//String value = o.get(key).toString();//
            		//System.out.println("key:"+key+" vlaue:"+value);
            		sb.append(key);
                    sb.append("\u0001");
            	}
            	sb.append("\u0002");
                
                // 开始时间
                long stime = System.currentTimeMillis();


				/*
				 * try { list.parallelStream()..forEachOrdered(entity ->
				 * sb.append(appendContainer(entity))); } catch (Exception e) {
				 * e.printStackTrace(); }
				 */
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   

                for (int nRow = 0; nRow < nContainerCount; nRow++) {
                	Map<String, Object> entity = list.get(nRow);
                	for(String key:entity.keySet()){
                		//keySet获取map集合key的集合  然后在遍历key即可
                		//String value = entity.get(key).toString();//
                		//System.out.println("key:"+key+" vlaue:"+value);
                		if (entity.get(key) == null) {
							sb.append("");
						} else if (entity.get(key) instanceof java.util.Date) {
							sb.append(f.format(entity.get(key)));
						} else {
							sb.append(entity.get(key));
						}
						sb.append("\u0001");
                	}
                	sb.append("\u0002");
                }
                sb.append("\u0003");
                // 结束时间
                long etime = System.currentTimeMillis();
                // 计算执行时间
                System.out.printf("执行时长：%d 毫秒.", (etime - stime));
            }


            // 结束时间
            stopWatch2.stop();
            // 统计执行时间（秒）
            sbSummer.append("TIMINGSTRING " + stopWatch2.getTotalTimeSeconds());
            sbSummer.append(sb.toString());
            return RestResult.suc(sbSummer.toString());
        } catch (Exception ex) {
        	ex.printStackTrace();
            return RestResult.fail(500, "失败了", ex.getMessage());
        }

    }

    private String appendContainer(ContainerEntity entity) {

        StringBuilder sb = new StringBuilder();
        Field[] fields = entity.getClass().getDeclaredFields();
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        

        try {
            for (int nColIndex = 0; nColIndex < fields.length; nColIndex++) {
            	fields[nColIndex].setAccessible(true);
            	if (fields[nColIndex].getType().toString().equals("class java.util.Date") ) {                   
                   if (fields[nColIndex].get(entity)==null)
                       sb.append("");
                   else
                       sb.append(f.format(fields[nColIndex].get(entity)));
                } else {
                    if (fields[nColIndex].get(entity)==null)
                        sb.append("");
                    else
                        sb.append(fields[nColIndex].get(entity));
                }
                sb.append(nColIndex != nColCount - 1 ? "\u0001" : "\u0002");
            }
        } catch (Exception ex) {
            System.out.println(ex);
        }

        return sb.toString();
    }

    /**
     * 自定义Oracle SQL根据id查询集装箱信息
     *
     * @param containerId 用户id
     * @return 返回查询集装箱对象
     */
    @GetMapping("/getById/{containerId}")
    public ContainerEntity getById(@PathVariable Long containerId) {
        ContainerEntity userEntity = iUserService.getContainerById(containerId);
        return userEntity;
    }

    /**
     * 获取属性名数组
     */
    private String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

}